package com.sse.product.exception;


import com.sse.product.common.ResultCode;
import com.sse.product.model.rbac.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName GlobalExceptionHandler
 * @Description TODO
 * @Author junyongli
 * @Date 2022/6/29 11:02
 * @Version 1.0
 **/
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = ProductRuntimeException.class)
    @ResponseBody
    public ResponseEntity<ResponseVo<Object>> gatewayRuntimeException(ProductRuntimeException e, HttpServletResponse response){
        log.error("[GlobalExceptionHandler.gatewayRuntimeException] throw exception - ", e);
        return new ResponseEntity<>(
                ResponseVo.assemble(e.getCode(),  e.getMsg()),
                new HttpHeaders(), HttpStatus.OK
        );
    }

    @ExceptionHandler({AccessDeniedException.class})
    public void accessDeniedExceptionHandler(AccessDeniedException e) {
        throw e;
    }


    @ExceptionHandler(value = BizRuntimeException.class)
    @ResponseBody
    public ResponseEntity<ResponseVo<Object>> bizRuntimeException(BizRuntimeException e, HttpServletResponse response){
        log.error("[GlobalExceptionHandler.bizRuntimeException] throw exception - ", e);
        return new ResponseEntity<>(
                ResponseVo.assemble(ResultCode.BIZ_ERROR, e.getMsg()),
                new HttpHeaders(), HttpStatus.OK
        );
    }


    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseEntity<ResponseVo<Object>> exception(Exception e, HttpServletResponse response){
        log.error("[GlobalExceptionHandler.exception] throw exception - ", e);
        return new ResponseEntity<>(
                //一般情况考虑到用户友好及安全，不返回详细错误信息
                //ResponseVo.assemble(ResultCode.SYSTEM_ERROR),
                //应用对内服务的情况，可以返回详细报错信息，便于调试定位
                ResponseVo.assemble(ResultCode.SYSTEM_ERROR, e.getMessage()),
                new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR
        );
    }
}
